// 示例数据
const inventoryData = [{
		id: 1,
		jtektModel: 'TG517-006040',
		customerModel: 'C1',
		backNumber: 'B12',
		bookQuantity: 100,
		boxDatas: [{
			id: 1,
			boxCount: '5',
			standardQuantity: '6',
			actualCount: '30'
		}, {
			id: 2,
			boxCount: '2',
			standardQuantity: '5',
			actualCount: '10'
		}, {
			id: 3,
			boxCount: '3',
			standardQuantity: '7',
			actualCount: '21'
		}]
	},
	{
		id: 2,
		jtektModel: 'TG517-006041',
		customerModel: 'C6',
		backNumber: 'B67',
		bookQuantity: 200,
		boxDatas: [{
			id: 1,
			boxCount: '3',
			standardQuantity: '2',
			actualCount: '6'
		}]
	},
	{
		id: 3,
		jtektModel: 'TG517-006042',
		customerModel: 'C5',
		backNumber: 'B54',
		bookQuantity: 150,
		boxDatas: [{
			id: 1,
			boxCount: '7',
			standardQuantity: '3',
			actualCount: '21'
		}, {
			id: 2,
			boxCount: '2',
			standardQuantity: '6',
			actualCount: '12'
		}]
	},
	{
		id: 4,
		jtektModel: 'TG517-006043',
		customerModel: 'C5',
		backNumber: 'B54',
		bookQuantity: 150,
		boxDatas: [{
			id: 1,
			boxCount: '7',
			standardQuantity: '3',
			actualCount: '21'
		}, {
			id: 2,
			boxCount: '2',
			standardQuantity: '6',
			actualCount: '12'
		}]
	}
];

let currentItemId = null;
let boxData = [];
let isSearched = false;

// DOM 加载完成后执行
document.addEventListener('DOMContentLoaded', function() {
	// 设置默认日期为今天
	document.getElementById('inventoryDate').valueAsDate = new Date();

	// 初始化表格数据
	renderInventoryTable();

	// 绑定事件监听器
	document.getElementById('searchBtn').addEventListener('click', handleSearch);
	document.getElementById('submitBtn').addEventListener('click', handleSubmit);
	document.getElementById('addBoxBtn').addEventListener('click', addBoxRow);
	document.getElementById('confirmBtn').addEventListener('click', confirmInventory);

	// 模态框关闭时清除数据
	const detailModal = document.getElementById('detailModal');
	detailModal.addEventListener('hidden.bs.modal', function() {
		clearModalData();
	});
});

// 渲染盘点表格
function renderInventoryTable() {
	const tableBody = document.getElementById('inventoryTableBody');
	tableBody.innerHTML = '';

	// 如果没有查询过，显示空表格
	if (!isSearched) {
		const emptyRow = document.createElement('tr');
		emptyRow.innerHTML = `
      <td colspan="6" class="text-center">请先进行查询</td>
    `;
		tableBody.appendChild(emptyRow);
		return;
	}

	inventoryData.forEach(item => {
		const count = item.actualCount || '';
		const difference = item.difference || '';
		const row = document.createElement('tr');

		// 设置差异的颜色
		let differenceClass = '';
		if (typeof difference === 'number') {
			if (difference > 0) {
				differenceClass = 'difference-positive';
			} else if (difference < 0) {
				differenceClass = 'difference-negative';
			} else {
				differenceClass = 'difference-zero';
			}
		}

		row.innerHTML = `
      <td>${item.jtektModel}</td>
      <td>${item.customerModel}</td>
      <td>${item.backNumber}</td>
      <td>${item.bookQuantity}</td>
      <td class="clickable-cell" data-id="${item.id}">${count || ''}</td>
      <td class="${differenceClass}">${difference}</td>
    `;

		tableBody.appendChild(row);

		// 为盘点数字单元格添加事件监听器
		const countCell = row.querySelector('.clickable-cell');
		countCell.addEventListener('click', function() {
			const id = parseInt(this.getAttribute('data-id'));
			openDetailModal(id);
		});
	});
}

// 更新差异值
function updateDifference(id, actualCount) {
	const item = inventoryData.find(item => item.id === id);
	if (item) {
		item.actualCount = actualCount;
		item.difference = item.bookQuantity - actualCount;
		renderInventoryTable();
	}
}

// 打开详情模态框
function openDetailModal(id) {
	currentItemId = id;
	const item = inventoryData.find(item => item.id === id);

	if (item) {
		document.getElementById('modalModel').value = item.jtektModel;
		document.getElementById('modalCount').value = item.actualCount || '';

		// 将当前行的boxDatas赋值给boxData
		boxData = item.boxDatas ? [...item.boxDatas] : [];

		// 如果没有数据，初始化一个空行
		if (boxData.length === 0) {
			boxData = [{
				id: 1,
				boxCount: '',
				standardQuantity: '',
				actualCount: ''
			}];
		}

		renderBoxTable();
	}

	// 显示模态框
	const modal = new bootstrap.Modal(document.getElementById('detailModal'));
	modal.show();
}

// 渲染箱数表格
function renderBoxTable() {
	const tableBody = document.getElementById('boxTableBody');
	tableBody.innerHTML = '';

	boxData.forEach(box => {
		const row = document.createElement('tr');
		row.innerHTML = `
      <td>
        <input type="number" class="form-control box-count" min="0"
               data-id="${box.id}" value="${box.boxCount || ''}">
      </td>
      <td>
        <input type="number" class="form-control standard-quantity" min="0"
               data-id="${box.id}" value="${box.standardQuantity || ''}">
      </td>
      <td>
        <input type="number" class="form-control actual-count" min="0"
               data-id="${box.id}" value="${box.actualCount || ''}" disabled>
      </td>
      <td>
        <button class="btn btn-sm btn-danger delete-box" 
                data-id="${box.id}">删除</button>
      </td>
    `;

		tableBody.appendChild(row);

		// 为箱数输入框添加事件监听器
		const boxCountInput = row.querySelector('.box-count');
		boxCountInput.addEventListener('input', calculateRowTotal);

		// 为标准数量输入框添加事件监听器
		const standardInput = row.querySelector('.standard-quantity');
		standardInput.addEventListener('input', calculateRowTotal);

		// 为删除按钮添加事件监听器
		const deleteBtn = row.querySelector('.delete-box');
		deleteBtn.addEventListener('click', function() {
			const boxId = parseInt(this.getAttribute('data-id'));
			deleteBox(boxId);
		});
	});

	// 计算并更新总盘点数
	updateTotalCount();
}

// 计算行的盘点数
function calculateRowTotal() {
	const row = this.closest('tr');
	const boxId = parseInt(this.getAttribute('data-id'));
	const boxCount = parseInt(row.querySelector('.box-count').value) || 0;
	const standardQuantity = parseInt(row.querySelector('.standard-quantity').value) || 0;
	const actualCount = boxCount * standardQuantity;

	// 更新当前行的盘点数
	row.querySelector('.actual-count').value = actualCount;

	// 更新箱数据
	const box = boxData.find(b => b.id === boxId);
	if (box) {
		box.boxCount = boxCount;
		box.standardQuantity = standardQuantity;
		box.actualCount = actualCount;
	}

	// 更新总盘点数
	updateTotalCount();
}

// 删除箱子
function deleteBox(boxId) {
	// 至少保留一行
	if (boxData.length <= 1) {
		alert('至少保留一行数据');
		return;
	}

	boxData = boxData.filter(box => box.id !== boxId);
	renderBoxTable();
}

// 添加箱子行
function addBoxRow() {
	const newId = boxData.length > 0 ? Math.max(...boxData.map(box => box.id)) + 1 : 1;

	boxData.push({
		id: newId,
		boxCount: '',
		standardQuantity: '',
		actualCount: ''
	});

	renderBoxTable();
}

// 更新总盘点数
function updateTotalCount() {
	const totalCount = boxData.reduce((sum, box) => {
		// 将actualCount转为数字，如果无法转换则为0
		const count = parseInt(box.actualCount) || 0;
		return sum + count;
	}, 0);

	document.getElementById('modalCount').value = totalCount;
}

// 确认盘点
function confirmInventory() {
	const totalCount = parseInt(document.getElementById('modalCount').value) || 0;

	if (currentItemId !== null) {
		// 将当前的boxData赋值给当前行的boxDatas
		const item = inventoryData.find(item => item.id === currentItemId);
		if (item) {
			item.boxDatas = [...boxData];
		}

		updateDifference(currentItemId, totalCount);

		// 关闭模态框
		const modal = bootstrap.Modal.getInstance(document.getElementById('detailModal'));
		modal.hide();

		// 显示成功提示
		//alert('盘点数据已更新！');
	}
}

// 清除模态框数据
function clearModalData() {
	currentItemId = null;
	boxData = [];
	document.getElementById('modalModel').value = '';
	document.getElementById('modalCount').value = '';
}

// 处理查询按钮点击
function handleSearch() {
	const inventoryNum = document.getElementById('inventoryNum').value.trim();

	// 检查盘点单号是否为空
	if (!inventoryNum) {
		alert('盘点单号不能为空！');
		return;
	}

	// 模拟查询，这里可以添加实际的查询逻辑
	const company = "JCC";
	const warehouse = "重庆特兰富力仓库";

	// 反写公司和仓库
	document.getElementById('company').value = company;
	document.getElementById('warehouse').value = warehouse;

	// 标记为已查询
	isSearched = true;

	// 重新渲染表格
	renderInventoryTable();

	//alert(`查询盘点单号：${inventoryNum}`);
}
// 处理提交按钮点击
function handleSubmit() {
	// 如果没有查询过数据，提示并返回
	if (!isSearched) {
		alert('请先查询数据！');
		return;
	}
	if (confirm('是否确认提交？')) {
		// 模拟提交成功
		alert('提交成功！');
		// 清除表格数据
		clearFormData();
	}
}

// 清除表单数据
function clearFormData() {
	// 清除公司和仓库
	document.getElementById('company').value = '';
	document.getElementById('warehouse').value = '';

	// 重置查询状态
	isSearched = false;

	// 清空盘点数据
	inventoryData.forEach(item => {
		item.actualCount = undefined;
		item.difference = undefined;
		item.boxDatas = []; // 清空箱数据
	});

	// 重新渲染表格
	renderInventoryTable();
}